import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { token } from '@/utils/storage'
import CommonErrorStatus from '../CommonErrorStatus';
import MainErrorStatus from './MainErrorStatus';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_MAIN_BACKEND_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 120000 // request timeout
});

const commonErrorStatus = new CommonErrorStatus();

const errorStatus = new MainErrorStatus();

// request interceptor
service.interceptors.request.use(
  (config: any) => {
    // do something before request is sent
    if (token.get()) {
      (config.headers as any)["X-Access-Token"] = token.get();
      (config.headers as any).Authorization = token.get();
      (config.headers as any)["Content-Type"] = "application/json;charset=UTF-8";
    }
    return config
  },
  (error: any) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response: any) => {
    const res = response ? response.data : {};

    // if the custom code is not 20000, it is judged as an error.
    if (!/[2][0-9]*/.test(res.status_code.toString())) {
      if ((errorStatus as any)[res.status_code.toString()]) {
        (errorStatus as any)[res.status_code.toString()]();
      }
    } else {
      return response.data;
    }
  },
  (error: any) => {
    if (error.response) {
      if (error.response.status && (commonErrorStatus as any)[error.response.status.toString()]) {
        (commonErrorStatus as any)[error.response.status.toString()](error.response);
      } else {
        commonErrorStatus.default();
      }
    }
    return Promise.reject(error)
  }
)

export default service
